<?php
/**
 * Created by PhpStorm
 * USER MingTingLiang   QQ 915802070
 * Date 2020-12-15-015   11:23
 */


require "INews.php";
require "IPlugin.php";

class  NewsDetail implements INews
{
    public $news_data;
    public $news_id = 0;
    public $plugs = [];

    public function __construct($news_id)
    {
        $newsFormDatabase = [
            ["news_id" => "101", "news_title" => "八国联军", "news_content" => "被打败",],
            ["news_id" => "102", "news_title" => "毛主席", "news_content" => "当选人民主席",],

        ];

        $this->news_id = $news_id;
        $this->news_data = $newsFormDatabase;

//        $clickPlugin = new ClickPlugin();
//        $this->regPlug($clickPlugin);
        $this->scanPlugins();    //被观察者去扫描
    }

    public function scanPlugins()
    {
        $scanDir = __DIR__ . "/plugins/";
        //   die($scanDir);
        $fileList = scandir($scanDir);
//        var_dump($fileList);
        foreach ($fileList as $index => $file) {

            if (is_file($scanDir . $file)) {
                $classname = basename($file, ".php");
                require $scanDir . $file;
                $classObject = new $classname($this);
                if (is_subclass_of($classObject, "IPlugin")) {
                    $this->regPlug($classObject);

                }
            }
        }

    }

    public function getNews()
    {
        foreach ($this->news_data as $index => $news) {
            if ($this->news_id == $news["news_id"]) {
                return $news;
            }
        }
    }

    public function display()
    {
        $get_news = $this->getNews();

        echo "<h2>{$get_news['news_title']}</h2>";
        echo "<div>{$get_news['news_content']}</div>";

        foreach ($this->plugs as $plugName => $plugObject) {
            $plugObject->update($this->news_id);
        }

    }

    public function regPlug(IPlugin $plugin)
    {
        // TODO: Implement regPlug() method.
        $this->plugs[strval($plugin)] = $plugin;
    }

    public function unregPlug(IPlugin $plugin)
    {
        // TODO: Implement unregPlug() method.
    }
}